<template>
  <t-drawer
    :visible="internalVisible"
    :header="isEdit ? '编辑账号' : '新增账号'"
    size="600px"
    placement="right"
    :confirm-btn="{ content: '保存', loading: saveLoading }"
    @confirm="handleSave"
    @close="handleClose"
  >
    <t-form
      ref="accountForm"
      :data="formData"
      :rules="formRules"
      label-align="right"
      label-width="100px"
    >
      <t-form-item label="所属部门" name="deptId">
        <t-tree-select
          v-model="formData.deptId"
          :data="deptTreeData"
          :keys="treeKeys"
          placeholder="请选择所属部门"
          clearable
          filterable
          :popup-props="{ attach: 'body' }"
        />
      </t-form-item>

      <t-form-item label="所属角色" name="roleIds">
        <t-select
          v-model="formData.roleIds"
          placeholder="请选择角色"
          multiple
          clearable
          :loading="roleLoading"
          :popup-props="{ attach: 'body' }"
        >
          <t-option
            v-for="role in roleOptions"
            :key="role.id"
            :value="role.id"
            :label="role.name"
          >
            {{ role.name }}
          </t-option>
        </t-select>
      </t-form-item>

      <t-form-item label="用户名" name="username">
        <t-input
          v-model="formData.username"
          placeholder="请输入用户名"
          maxlength="50"
          :disabled="isEdit"
        />
      </t-form-item>

      <t-form-item label="密码" name="password">
        <t-input
          v-model="formData.password"
          placeholder="请输入登录密码"
          maxlength="50"
          type="password"
          :disabled="isEdit"
        />
        <!-- <div v-if="!isEdit" style="font-size: 12px; color: #666; margin-top: 4px;">
          默认密码：Admin123
        </div> -->
      </t-form-item>

      <t-form-item label="昵称" name="nickname">
        <t-input
          v-model="formData.nickname"
          placeholder="请输入昵称"
          maxlength="50"
        />
      </t-form-item>

      <t-form-item label="邮箱" name="email">
        <t-input
          v-model="formData.email"
          placeholder="请输入邮箱地址"
          maxlength="100"
          type="email"
        />
      </t-form-item>

      <t-form-item label="手机" name="phone">
        <t-input
          v-model="formData.phone"
          placeholder="请输入手机号"
          maxlength="11"
        />
      </t-form-item>

      <t-form-item label="备注" name="remark">
        <t-textarea
          v-model="formData.remark"
          placeholder="请输入备注信息"
          maxlength="200"
          :autosize="{ minRows: 3, maxRows: 5 }"
        />
      </t-form-item>

      <t-form-item label="状态" name="status">
        <t-select
          v-model="formData.status"
          placeholder="请选择状态"
          :popup-props="{ attach: 'body' }"
        >
          <t-option :value="1" label="启用" />
          <t-option :value="0" label="禁用" />
        </t-select>
      </t-form-item>
    </t-form>
  </t-drawer>
</template>

<script>
import {
  Drawer as TDrawer,
  Form as TForm,
  FormItem as TFormItem,
  Select as TSelect,
  Option as TOption,
  Input as TInput,
  Textarea as TTextarea,
  TreeSelect as TTreeSelect,
} from 'tdesign-vue';
import { getRoleList } from '@/api/role';
import { createUser } from '@/api/account';

export default {
  name: 'AccountFormDrawer',
  components: {
    TDrawer,
    TForm,
    TFormItem,
    TSelect,
    TOption,
    TInput,
    TTextarea,
    TTreeSelect,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    currentEditData: {
      type: Object,
      default: null,
    },
    deptTreeData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      saveLoading: false,
      roleLoading: false,

      // 树配置
      treeKeys: {
        value: 'id',
        label: 'name',
        children: 'children',
      },

      // 表单数据
      formData: {
        deptId: null,
        roleIds: [],
        username: '',
        password: 'Admin123',
        nickname: '',
        email: '',
        phone: '',
        remark: '',
        status: 1,
      },

      // 表单验证规则
      formRules: {
        deptId: [
          { required: false, message: '请选择所属大区', trigger: 'change' },
        ],
        roleIds: [
          { required: true, message: '请选择角色', trigger: 'change' },
          { type: 'array', min: 1, max: 3, message: '请选择1-3个角色', trigger: 'change' },
        ],
        username: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
          { min: 4, message: '账号至少4个字符', trigger: 'blur' },
          { max: 20, message: '账号不能超过20个字符', trigger: 'blur' },
          { pattern: /^[\s\S]+$/, message: '账号格式不正确', trigger: 'blur' },
        ],
        password: [
          {
            validator: (val) => {
              if (!val && !this.isEdit) {
                return { result: false, message: '请输入密码' };
              }
              if (val) {
                if (!/^\S*(?=\S{6})(?=\S*\d)(?=\S*[A-Z])\S*$/i.test(val)) {
                  return { result: false, message: '密码必须包含数字、字母，长度为6-16' };
                }
              }
              return { result: true };
            },
            trigger: 'blur'
          }
        ],
        nickname: [
          { required: false },
        ],
        email: [
          {
            validator: (value) => {
              if (!value) return { result: true }; // 空值不验证
              const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
              if (!emailRegex.test(value)) {
                return { result: false, message: '请输入正确的邮箱格式' };
              }
              return { result: true };
            },
            trigger: 'blur'
          },
        ],
        phone: [
          { required: false },
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' },
          { type: 'number', enum: [0, 1], message: '状态值不正确', trigger: 'change' },
        ],
        remark: [
          { required: false },
        ],
      },

      // 角色选项
      roleOptions: [],
    };
  },

  computed: {
    internalVisible: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit('update:visible', value);
      },
    },
  },

  watch: {
    visible(val) {
      if (val) {
        this.initFormData();
        this.getRoleOptions();
      }
    },
  },

  methods: {
    // 获取角色选项
    async getRoleOptions() {
      this.roleLoading = true;
      try {
        const response = await getRoleList({ page: 1, pageSize: 100 });
        if (response?.data?.code === 200) {
          this.roleOptions = response.data.data?.items || [];
        } else {
          // 使用模拟数据
          this.roleOptions = [
            { id: 1, name: '管理员' },
            { id: 2, name: '普通用户' },
            { id: 3, name: '访客' },
          ];
        }
      } catch (error) {
        console.error('获取角色列表失败:', error);
        // 使用模拟数据
        this.roleOptions = [
          { id: 1, name: '管理员' },
          { id: 2, name: '普通用户' },
          { id: 3, name: '访客' },
        ];
      } finally {
        this.roleLoading = false;
      }
    },

    // 初始化表单数据
    initFormData() {
      if (this.isEdit && this.currentEditData) {
        this.formData = {
          deptId: this.currentEditData.deptId || null,
          roleIds: this.currentEditData.roleIds || [],
          username: this.currentEditData.username || '',
          password: '', // 编辑时不显示原密码
          nickname: this.currentEditData.nickname || '',
          email: this.currentEditData.email || '',
          phone: this.currentEditData.phone || '',
          remark: this.currentEditData.remark || '',
          status: this.currentEditData.status !== undefined ? this.currentEditData.status : 1,
        };
      } else {
        this.formData = {
          deptId: null,
          roleIds: [],
          username: '',
          password: 'Admin123', // 新增时使用默认密码
          nickname: '',
          email: '',
          phone: '',
          remark: '',
          status: 1,
        };
      }
    },

    // 保存账号
    async handleSave() {
      try {
        // 表单验证
        const valid = await this.$refs.accountForm.validate();
        if (!valid) return;

        this.saveLoading = true;

        // 准备提交数据
        const submitData = {
          deptId: this.formData.deptId,
          roleIds: this.formData.roleIds,
          username: this.formData.username,
          nickname: this.formData.nickname,
          email: this.formData.email,
          phone: this.formData.phone,
          remark: this.formData.remark,
          status: this.formData.status,
        };

        // 如果是新增，添加密码
        if (!this.isEdit) {
          submitData.password = this.formData.password;
          // 调用创建账号接口
          const res = await createUser(submitData);
          if (res?.data?.code === 200) {
            this.$message.success('创建账号成功');
            this.$emit('save', submitData);
            this.handleClose();
          } else {
            this.$message.error(res?.data?.message || '创建账号失败');
          }
        } else {
          // 编辑模式下发送保存事件给父组件
          this.$emit('save', submitData);
        }
      } catch (error) {
        console.error('保存账号失败:', error);
        this.$message.error(error?.response?.data?.message || '保存账号失败');
      } finally {
        this.saveLoading = false;
      }
    },

    // 关闭抽屉
    handleClose() {
      this.internalVisible = false;
      this.$emit('close');
      // 清除表单验证状态
      this.$nextTick(() => {
        if (this.$refs.accountForm) {
          this.$refs.accountForm.clearValidate();
        }
      });
    },

    // 设置保存状态
    setSaveLoading(loading) {
      this.saveLoading = loading;
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .t-drawer__body {
  padding: 24px;
}

/deep/ .t-form-item {
  margin-bottom: 24px;
}

// 确保label右对齐
/deep/ .t-form__label {
  text-align: right !important;
  justify-content: flex-end !important;
}

/deep/ .t-form-item__label {
  text-align: right !important;
  justify-content: flex-end !important;
}

// 确保抽屉内的下拉菜单有正确的z-index
/deep/ .t-select__popup {
  z-index: 10000 !important;
}

/deep/ .t-popup {
  z-index: 10000 !important;
}

// 确保选择框的样式正确
/deep/ .t-select {
  width: 100%;
}

/deep/ .t-tree-select {
  width: 100%;
}
</style>